package com.dabaozhan.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;

import com.google.gson.Gson;
import com.qiniu.AccountMgr;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import org.apache.commons.lang.StringUtils;


public class ImageOperation {

	public static void main(String[] args) {

		///Users/houzhong/Downloads/WechatIMG14.jpeg
		String ste = ImageToBase64ByOnline("http://qiniudns.zaishengwang.com/WechatIMG14.jpeg");
		System.out.println(ste);
		//Base64ToImage(ste, "/Users/houzhong/Downloads/testimg/test2.jpg");
		/*String img = ImageUtils.getImgStr("https://www.zaishengwang.com/fileImage/1540551582323.jpg");

		String ste = ImageToBase64ByOnline(img);
		Base64ToImage(ste, "/Users/houzhong/Downloads/testimg/test2.jpg");*/


//		String targetUrl = "https://www.zaishengwang.com/fileImage/1540551582323.jpg";
//
//		//System.out.println(targetUrl.substring(targetUrl.lastIndexOf("/")));
//
//		String url = "https://www.zaishengwang.com/fileImage/1540556063284.png";
//		String aString = getDomain(url);
//		if (aString.equals("zaishengwang.com")) {
//			System.out.println(111);
//		}else {
//			System.out.println(222);
//		}
		//new ImageOperation().download(targetUrl,"/Users/houzhong/Downloads/testimg/");
		
	}
	
    public static String getDomain(String url){
        String regex = "^.*?://(?:[a-zA-Z]+[.])?(\\w+([.]\\w+)*)/.*$"; 
        Matcher matcher = Pattern.compile(regex).matcher(url);
        String result = null;
        if(matcher.find()){
            result = matcher.group(1);
        }
        return result;
    }
	
	/**
	 * 在线图片转换成base64字符串
	 * 
	 * @param imgURL	图片线上路径
	 * @return
	 *
	 * @author ZHANGJL
	 * @dateTime 2018-02-23 14:43:18
	 */
	public static String ImageToBase64ByOnline(String imgURL) {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		try {
			// 创建URL
			URL url = new URL(imgURL);
			byte[] by = new byte[1024];
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			InputStream is = conn.getInputStream();
			// 将内容读取内存中
			int len = -1;
			while ((len = is.read(by)) != -1) {
				data.write(by, 0, len);
			}
			// 关闭流
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		Base64 encoder = new Base64();
		 
		return new String(encoder.decode(data.toByteArray()));
	}
	
	/**
	 * base64字符串转换成图片
	 * @param imgStr		base64字符串
	 * @param imgFilePath	图片存放路径
	 * @return
	 *
	 * @author ZHANGJL
	 * @dateTime 2018-02-23 14:42:17
	 */
	public static boolean Base64ToImage(String imgStr,String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
		Base64 encoder = new Base64();
		try {
			// Base64解码
			byte[] b = encoder.decode(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
 
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// 生成文件路径
	public static boolean createFolder(String folderPath){
		if(StringUtils.isBlank(folderPath)){
			return false;
		}
		File file = new File(folderPath);
		if(!file.exists()){
			file.mkdirs();
		}
		return true;
	}
	
	public static  boolean deleteFile(String sPath) {
		boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除  
        if (file.isFile() && file.exists()) {  
            file.delete();  
            flag = true;  
        }  
        return flag;  
    }  
	
	// 解码base64图片，并保存
	public static String encode64Image(String imageBase64,String path){
		String dataPrix = "";
		String suffix = "";
        String data = "";

		if(imageBase64 == null || "".equals(imageBase64)){
           // throw new Exception("上传失败，上传图片数据为空");
        }else{
            String [] d = imageBase64.split("base64,");
            if(d != null && d.length == 2){
                dataPrix = d[0];
                data = d[1];
            }
        }
		if ("".equals(data)) {
			data = imageBase64;
		}
		if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//编码的jpeg图片数据
            suffix = ".jpg";
        } else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//编码的icon图片数据
            suffix = ".ico";
        } else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//编码的gif图片数据
            suffix = ".gif";
        } else if("data:image/png;".equalsIgnoreCase(dataPrix)){//编码的png图片数据
            suffix = ".png";
        }else {
        	suffix = ".png";
        }
    	
    	Configuration cfg = new Configuration(Zone.autoZone());
        UploadManager uploadManager = new  UploadManager(cfg);
        
        //获取七牛账号和密钥
    	Auth auth = Auth.create(AccountMgr.ACCESS_KEY, AccountMgr.SECRET_KEY);
    	
    	//获取七牛空间
    	String uploadToken=auth.uploadToken(AccountMgr.BUCKET_NAME);
    	
		// 上传到七牛后保存的文件名
		String key = System.currentTimeMillis() + suffix;
   	 
		//目录不存在创建
		createFolder(path);
		
		byte[] decode = Base64.decodeBase64(data);
		int length = decode.length;
		for(int i=0;i<length;++i){
			if(decode[i] < 0){
				decode[i] += 256;
			}
		}
		OutputStream out = null;
		try {
			out = new FileOutputStream(new File(path+key));
			try {
				out.write(decode);
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		String pathStr = path + key;
		
		ImageUtils.scale(pathStr, pathStr, 1, true);
		
		try {
			//保存到七牛
		    Response response = uploadManager.put(pathStr, key, uploadToken);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		    System.out.println(putRet.key);
		    System.out.println(putRet.hash);
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    System.err.println(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		        //ignore
		    }
		}
		//上传完成删除本地图片
		deleteFile(pathStr);
		
		return key;
	}
	
	/**
	 * 上传
	 * @param image
	 * @param path
	 * @return
	 */
	public static String encodeImage(String image,String path){
		
		Configuration cfg = new Configuration(Zone.autoZone());
        UploadManager uploadManager = new  UploadManager(cfg);
        
        //获取七牛账号和密钥
    	Auth auth = Auth.create(AccountMgr.ACCESS_KEY, AccountMgr.SECRET_KEY);
    	
    	//获取七牛空间
    	String uploadToken = auth.uploadToken(AccountMgr.BUCKET_NAME);
		
		String pathStr = path + image;
		
		try {
			//保存到七牛
		    Response response = uploadManager.put(pathStr, image, uploadToken);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		    System.out.println(putRet.key);
		    System.out.println(putRet.hash);
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    System.err.println(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		        //ignore
		    }
		}
		//上传完成删除本地图片
		deleteFile(pathStr);
		
		return AccountMgr.SPACE_NAME + image;
	}

	
	 //密钥配置
    Auth auth = Auth.create(AccountMgr.ACCESS_KEY, AccountMgr.SECRET_KEY);

    /**
     * 获取下载文件路径，即：donwloadUrl
     * @return
     */
    public String getDownloadUrl(String targetUrl) {
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        return downloadUrl;
    }

	public static void download(String url, String filepath) {
        OkHttpClient client = new OkHttpClient();
        System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        okhttp3.Response resp = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if(resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                File imgFile = new File(filepath+url.substring(url.lastIndexOf("/")+1));
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }
    }
	
	private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0; 
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }


}
